document.addEventListener('DOMContentLoaded', function() {
    const groupsContainer = document.getElementById('groups-container');
    const addGroupBtn = document.getElementById('add-group');
    const saveBtn = document.getElementById('save-settings');
    const toggleSwitch = document.getElementById('toggle-switch');

    // 加载已保存的设置
    chrome.storage.sync.get(['keywordGroups', 'extensionEnabled'], function(result) {
        const groups = result.keywordGroups || [];
        const enabled = result.extensionEnabled !== undefined ? result.extensionEnabled : true;
        
        toggleSwitch.checked = enabled;
        groups.forEach((group, index) => {
            addGroupInput(group.keywords, group.color, index);
        });
        if (groups.length === 0) {
            addGroupInput('', '#FFFF00', 0);
        }
    });

    // 切换总开关状态
    toggleSwitch.addEventListener('change', function() {
        chrome.storage.sync.set({ extensionEnabled: this.checked });
    });

    // 添加新的关键词组输入
    addGroupBtn.addEventListener('click', function() {
        const groups = document.querySelectorAll('.group');
        addGroupInput('', '#FFFF00', groups.length);
    });

    // 保存设置
    saveBtn.addEventListener('click', function() {
        const groups = document.querySelectorAll('.group');
        const keywordGroups = [];

        groups.forEach(group => {
            const keywordsInput = group.querySelector('input[name="keywords"]');
            const colorInput = group.querySelector('input[name="color"]');
            
            if (keywordsInput.value.trim()) {
                keywordGroups.push({
                    keywords: keywordsInput.value,
                    color: colorInput.value
                });
            }
        });

        chrome.storage.sync.set({ keywordGroups }, function() {
            alert('设置已保存！刷新页面以应用高亮效果。');
        });
    });

    // 动态添加关键词组输入框
    function addGroupInput(keywords, color, index) {
        const groupDiv = document.createElement('div');
        groupDiv.className = 'group';
        groupDiv.innerHTML = `
            <input type="text" name="keywords" placeholder="输入关键词，用逗号分隔" value="${keywords}">
            <input type="color" name="color" value="${color}">
            <button class="remove-btn" data-index="${index}">移除</button>
        `;
        groupsContainer.appendChild(groupDiv);

        // 移除关键词组
        groupDiv.querySelector('.remove-btn').addEventListener('click', function() {
            groupDiv.remove();
        });
    }
});